package com.lianxueda.drawing.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.lianxueda.drawing.config.OssConfig;

import com.lianxueda.drawing.domain.pojo.Admins;
import com.lianxueda.drawing.domain.pojo.Teachers;
import com.lianxueda.drawing.mapper.AdminsMapper;
import com.lianxueda.drawing.mapper.TeacherMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import cn.dev33.satoken.util.SaResult;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author 29264
 */
@RestController
@RequestMapping("/api/avatar")
@RequiredArgsConstructor
@Tag(name = "图片模块", description = "图片模块接口")
public class AvatarController {

    private final OssConfig ossConfig;
    private final OSS ossClient;
    private final AdminsMapper adminsMapper;
    private final TeacherMapper teacherMapper;

    @PostMapping(value = "/uploadAvatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传管理员头像")
    public SaResult uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("id") Integer id) {
        String bucketName = ossConfig.getBucketName();
        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        if (!"jpg".equals(fileExt) && !"jpeg".equals(fileExt) && !"png".equals(fileExt)) {
            return SaResult.error("上传头像格式错误，仅支持(.jpg,.jpeg,.png)格式");
        }
        if (file.getSize() > 10 * 1024 * 1024) {
            return SaResult.error("上传头像大小不能超过10MB");
        }

        String uploadFileName = UUID.randomUUID().toString() + "_" + fileName;
        // 根据id查找管理员
        Admins admins = adminsMapper.selectById(id);
        if(admins == null){
            return SaResult.error("管理员不存在");
        }
        try {
            // 上传文件到 OSS
            PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, file.getInputStream());

            // 生成文件访问 URL 并更新数据库
            if (result != null) {
                // 设置有效期为两天（2 * 24 * 3600 * 1000 毫秒）
                Date expiration = new Date(System.currentTimeMillis() + 2 * 24 * 3600 * 1000);
                URL imageUrl = ossClient.generatePresignedUrl(bucketName, uploadFileName, expiration);

                // 将生成的图片 URL 更新到数据库中的用户头像字段中
                adminsMapper.updateAvatar(id, imageUrl.toString());

                // 创建一个 HashMap，将图片的 url 和 path 返回给客户端
                HashMap<String, String> response = new HashMap<>();
                response.put("url", imageUrl.toString());
                response.put("path", uploadFileName);

                return SaResult.ok().setData(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return SaResult.error("头像上传失败");
        }
        return SaResult.error("头像上传失败");
    }


    @PostMapping(value = "/uploadImg", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传教师头像")
    public SaResult uploadImg(@RequestParam("file") MultipartFile file, @RequestParam("id") Integer id) {
        String bucketName = ossConfig.getBucketName();
        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        if (!"jpg".equals(fileExt) && !"jpeg".equals(fileExt) && !"png".equals(fileExt)) {
            return SaResult.error("上传头像格式错误，仅支持(.jpg,.jpeg,.png)格式");
        }
        if (file.getSize() > 10 * 1024 * 1024) {
            return SaResult.error("上传头像大小不能超过10MB");
        }

        String uploadFileName = UUID.randomUUID().toString() + "_" + fileName;
        // 根据id查找管理员
        Teachers teachers = teacherMapper.selectById(id);
        if(teachers == null){
            return SaResult.error("教师不存在");
        }
        try {
            // 上传文件到 OSS
            PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, file.getInputStream());

            // 生成文件访问 URL 并更新数据库
            if (result != null) {
                // 设置有效期为两天（2 * 24 * 3600 * 1000 毫秒）
                Date expiration = new Date(System.currentTimeMillis() + 2 * 24 * 3600 * 1000);
                URL imageUrl = ossClient.generatePresignedUrl(bucketName, uploadFileName, expiration);

                // 将生成的图片 URL 更新到数据库中的用户头像字段中
                teacherMapper.updateAvatar(id, imageUrl.toString());

                // 创建一个 HashMap，将图片的 url 和 path 返回给客户端
                HashMap<String, String> response = new HashMap<>();
                response.put("url", imageUrl.toString());
                response.put("path", uploadFileName);

                return SaResult.ok().setData(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return SaResult.error("头像上传失败");
        }
        return SaResult.error("头像上传失败");
    }


}

